package cn.sylinx.hbatis.db.dialect.sql;

import java.util.regex.Pattern;

import cn.sylinx.hbatis.db.dialect.DbType;
import cn.sylinx.hbatis.ext.tool.RepositoryTools;
import cn.sylinx.hbatis.kit.Tuple;
import cn.sylinx.hbatis.log.GLog;

public class SqlServerSqlBuilder extends DefaultSqlBuilder {

	@Override
	public String[] buildCreateTableDDL(Class<?> clz) {

		String ddl = RepositoryTools.getInstance().generateTableDdlSql(DbType.SQLSERVER, clz);
		GLog.debug("dbType:{}, ddl: {}", DbType.SQLSERVER, ddl);
		String[] ddlArray = ddl.split(";\n");
		return ddlArray;
	}

	@Override
	public String[] buildModifyTableColumnDDL(Class<?> clz, String prop) {
		String ddl = RepositoryTools.getInstance().generateModifyTableColumnDDL(DbType.SQLSERVER, clz, prop);
		if (ddl == null) {
			return null;
		}
		GLog.debug("dbType:{}, ddl: {}", DbType.SQLSERVER, ddl);
		String[] ddlArray = ddl.split(";\n");
		return ddlArray;
	}

	@Override
	public String[] buildAddTableColumnDDL(Class<?> clz, String prop) {
		String ddl = RepositoryTools.getInstance().generateAddTableColumnDDL(DbType.SQLSERVER, clz, prop);
		GLog.debug("dbType:{}, ddl: {}", DbType.SQLSERVER, ddl);
		String[] ddlArray = ddl.split(";\n");
		return ddlArray;
	}

	@Override
	protected String[] getEscapeChar() {
		return new String[] { "[", "]" };
	}

	@Override
	public Tuple buildPaginatorSql(String preSql, int pageNumber, int pageSize) {

		String reg = "[oO][rR][dD][eE][rR]( )+[bB][yY]";
		Pattern p = Pattern.compile(reg);
		String[] split = p.split(preSql);
		String orderBy = null;
		if (split.length > 1) {
			preSql = split[0];
			orderBy = "order by" + split[1];
		} else {
			orderBy = "order by id desc";
		}

		String sqlCount = "select count(1) as totalCount from (" + preSql + ") as temp";
		int offset = pageSize * (pageNumber - 1);
		StringBuilder psql = new StringBuilder();
		psql.append("select top ").append(pageSize).append(" o.* from (");
		psql.append(" select row_number() over(").append(orderBy).append(") as rownumber,* from (");
		psql.append(preSql).append(") as oo) as o where rownumber > ").append(offset);
		String pageSql = psql.toString();
		GLog.debug("sqlserver page sql: {}", pageSql);

		Object[] params = new Object[] {};
		return Tuple.apply(sqlCount, pageSql, params);
	}

}
